<?php
/**
 * Created by PhpStorm.
 * User: Merdan
 * Date: 2017/3/28
 * Time: 13:25
 */

namespace App\Http\Controllers;


use App\Exceptions\BaseException;
use App\Http\Requests\CategoryRequest;
use App\Services\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    protected $categoryService;

    function __construct()
    {
        parent::__construct();
        $this->categoryService = new Category();
    }

    /**
     * 分类列表
     *
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        try{
            $limit = intval($request->get('count', 20));
            $categorys = $this->categoryService->getList($limit);
            return $this->success('',$categorys);
        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 获取单个分类信息
     *
     * @param $id
     * @return array
     */
    public function show($id)
    {
        try{
            $id = intval($id);
            $user = $this->categoryService->show($id);
            return $this->success('', $user);
        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 新增分类
     *
     * @param CategoryRequest $request
     * @return array
     */
    public function store(CategoryRequest $request)
    {
        try{
            $name = trim($request->get('name'));
            $this->categoryService->create(compact('name'));
            return $this->success('新增分类成功!');

        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 更新分类信息
     *
     * @param CategoryRequest $request
     * @param $id
     * @return array
     */
    public function update(CategoryRequest $request, $id)
    {
        try{
            $id = intval($id);
            $name = trim($request->get('name'));
            $this->categoryService->update($id, compact('name'));
            return $this->success('分类已更新!');
        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

}